package cn.smp.server.handler;

import cn.smp.message.GroupJoinRequestMessage;
import cn.smp.message.GroupJoinResponseMessage;
import cn.smp.server.session.Group;
import cn.smp.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        final String groupName = msg.getGroupName();
        final Group group = GroupSessionFactory.getGroupSession().joinMember(msg.getUsername(), groupName);
        if (group == null) {
            ctx.writeAndFlush(new GroupJoinResponseMessage(false,"群组不存在 "+groupName));
            return;
        }

        //发送加群成功消息
        ctx.writeAndFlush(new GroupJoinResponseMessage(false,"加入群组成功 "+groupName));

        //通知群成员
        final List<Channel> channels = GroupSessionFactory.getGroupSession().getMembersChannel(groupName);
        for (Channel channel : channels) {
            channel.writeAndFlush(new GroupJoinResponseMessage(true,"欢迎 "+msg.getUsername()+"加入本群"));
        }
    }
}
